<?php
/**
 * 评价类
 */

class Comment extends Order{
	
	private $tb_comment;

	function __construct() {
		parent::__construct('comment');
		$this->tb_comment = $this->get_tbname('comment');
	}
	
	public function comment($sn, $score_desc, $score_serv, $score_speed, $descs, $contents, $from = 0){
		if(empty($sn) || !isset($score_desc) || !isset($score_serv) || !isset($score_speed)){
			return $this->rwarn('请填写完整的评价信息');
		}
		if(empty($from)){
			$userinfo = & VS::get('userinfo');
		}else{
			$userinfo = & VS::get('managerinfo');
		}
		$orderinfo = $this->get_order_by_sn($sn);
		foreach ($descs as $goodsid => $desc_list){
			foreach($desc_list as $order_goodsid => $s_desc){
				$s_desc = $s_desc == 0 ? $score_desc : $s_desc;
				$average_score = $this->cal_average_score($sn, $s_desc, $score_serv, $score_speed);
				$id = $this->db->get_col($this->tb_comment, array('sn' => $sn, 'goodsid' => $goodsid, 'order_goodsid' => $order_goodsid), 'id');
				
				$data = array(
					'from'			=> $from,
					'userid'		=> $userinfo['userid'],
					'username'		=> $userinfo['username'],
					'orderid'		=> $orderinfo['id'],
					'sn'			=> $sn,
					'goodsid'		=> $goodsid,
					'order_goodsid'	=> $order_goodsid,
					'score_desc'	=> $s_desc,
					'score_serv'	=> $score_serv,
					'score_speed'	=> $score_speed,
					'score'			=> $average_score,
					'content'		=> $contents[$goodsid][$order_goodsid],
					'datetime'		=> date('Y-m-d H:i:s'),
				);
				if($id > 0){
					$data['updatetime'] = TIME; 
					$r = $this->db->update($this->tb_comment, array('id' => $id), $data);
				}else{
					$data['addtime'] = TIME;
					$r = $id = $this->db->insert($this->tb_comment, $data);
					
				}
				if($r > 0){
					$r = $this->update_goods_score($sn, $goodsid);
				}
				if($r < 0){
					return $this->rfail('入库失败');
				}
			}
		}
		// 计算商店得分
		$this->cal_shop_score();

		// 将订单状态置为已评价
		// $oOrder = & Order::instance();
		$this->commented($sn);
		return $this->rjust($r, $data);
	}
	
	// 更新商品动态表分数
	public function update_goods_score($sn, $goodsid){
		$total_score = $this->db->get_sum($this->tb_comment, 'score', array('goodsid' => $goodsid));
		$comment_count = $this->db->get_counts($this->tb_comment, array('goodsid' => $goodsid));
		$score = $total_score / $comment_count;
		
		$type_arr = array('desc', 'serv', 'speed');
		$scores = array();
		foreach($type_arr as $type){
			$total_score = $this->db->get_sum($this->tb_comment, "score_{$type}", array('goodsid' => $goodsid));
			$scores[$type] = array(
				'score'	=> $total_score / $comment_count,
				'detail'=> array(),
			);
			for($i = 1; $i <= 5; $i ++){
				$count = $this->db->get_counts($this->tb_comment, array('goodsid' => $goodsid, "score_{$type}" => $i));
				$scores[$type]['detail'][$i] = array(
					'count' => $count, 
					'rate' => $count * 100 / $comment_count,
				);
			}
		}
		$data = array(
			'comments'		=> $comment_count,
			'score'			=> $score,
			'scores'		=> serialize($scores),
		);
		$oGoods = & Goods::instance();
		return $oGoods->update_trends($goodsid, $data);
	}
	
	// 计算平均分
	public function cal_average_score($sn, $score_desc, $score_serv, $score_speed){
		$average_score = ($score_desc + $score_serv + $score_speed) / 3;
		return $average_score;
	}
	
	public function cal_shop_score(){
		$total_score = $this->db->get_sum($this->tb_comment, 'score');
		$comment_count = $this->db->get_counts($this->tb_comment);
		$shop_score = $total_score / $comment_count;
		
		shop_config_set('shop_score', $shop_score);
		return $shop_score;
	}
				
	/**
	 * 删除评价，仅标识，不作物理删除
	 */
	public function del($post){
		if(!is_array($post['list']))$post['list'] = array($post['list']);
		$iRtn = 0;
		foreach($post['list'] as $id){
			$r = $this->db->update($this->tb_comment, array('id' => $id), array('isdel' => 1));
			
			if($r > 0){
				$iRtn ++;
			}
		}
		return $iRtn;
	}
	
	
	/***************************************************************************
	 * 查询
	 ***************************************************************************/
	
	public function get_shop_score(){
		$shop_score = shop_config_get('score');
		if($shop_score == null){
			$shop_score = $this->cal_shop_score();
		}
		return $shop_score;
	}
	
	/**
	 * 取一条记录
	 */
	/*public function get_row($id, $fields = '*', $cache = false){
		return $this->db->get_row($this->tb_comment, array('id' => $id), $fields);

	}*/
	
	/**
	 * 取列表
	 */
	public function get_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10, $offset = PAGE_OFFSET){
		$where = array();
		$like = array();

		// 指定用户
		if(!empty($select['userid'])){			$where[] = "`c`.`userid`='{$select['userid']}'";						}

		if(!empty($select['keyword'])){
			$select['sn']			= $select['keyword'];
			$select['content']		= $select['keyword'];
			$select['goodsname']	= $select['keyword'];
		}
		if(!empty($select['sn'])){				$like[] = "`c`.`sn` LIKE '%{$select['sn']}%'";							}
		if(!empty($select['username'])){		$like[] = "`c`.`username` LIKE '%{$select['username']}%'";				}
		if(!empty($select['content'])){			$like[] = "`c`.`content` LIKE '%{$select['content']}%'";				}

		// 得分
		if(!empty($select['type'])){
			switch($select['type']){
				case '1':
					$where[] = "`score`>=1 AND `score`<2";
					break;
				case '2':
					$where[] = "`score`>=2 AND `score`<3";
					break;
				case '3':
					$where[] = "`score`>=3 AND `score`<4";
					break;
				case '4':
					$where[] = "`score`>=4 AND `score`<5";
					break;
				case '5':
					$where[] = "`score`=5";
					break;
			}
		}
		if(!empty($select['score_desc'])){			$where[] = "`c`.`score_desc`='{$select['score_desc']}'";			}
		if(!empty($select['score_serv'])){			$where[] = "`c`.`score_serv`='{$select['score_serv']}'";			}
		if(!empty($select['score_speed'])){			$where[] = "`c`.`score_speed`='{$select['score_speed']}'";			}
		
		if(!empty($select['goodsname'])){			
			$like[] = " EXISTS (SELECT `goodsid` FROM `{$this->tb_order_goods}` AS `g` WHERE `g`.`goodsid`=`c`.`order_goodsid` AND `g`.`goodsname` LIKE '%{$select['goodsname']}%')";
		}
		if(!empty($like)){
			$where[] = '('.(implode(' OR ', $like)).')';
		}
		$where[] = "`c`.`isdel`=0";	// 只显示未删除
		if(empty($where)){
			$where = '';
		}else{
			$where = " WHERE ".trim(implode(' AND ', $where));
		}

		// 排序
		$orderby = array();
		if(!empty($order)){
			$allfields = $this->db->get_fields($this->tb_comment);
			foreach ($order as $field => $direction){
				if(!in_array($direction, array('ASC', 'DESC', 'asc', 'desc')))continue;
				if(array_key_exists($field, $allfields)){
					$orderby[] = "`c`.`{$field}` {$direction}";
				}
			}
		}
		if(empty($orderby)){
			$orderby[] = "`c`.`id` DESC";
		}
		$orderby = implode(',', $orderby);

		$sql = <<<SQL
SELECT SQL_CALC_FOUND_ROWS {$fields} FROM `{$this->tb_comment}` AS `c`
	{$where}
	ORDER BY {$orderby} 
SQL
;
		$list = $this->db->sql_list($sql, $page, $size, $offset);
		//$list = $this->db->get_list($this->tb_comment, $fields, $select, $order, $page, $size, $offset);
		if(!empty($list['list'])){
			//$oOrder = & Order::instance();
			$oGoods = & Goods::instance();
			foreach ($list['list'] as $key => $row){
				// 订单信息
				$baseinfo = $oGoods->get_row($row['goodsid'], '`cover`');
				$row['goodsinfo'] = $this->get_order_goods($row['sn'], $row['goodsid']);
				$row['goodsinfo']['specs'] = unserialize($row['goodsinfo']['specs']);
				$row['goodsinfo']['fspecs'] = unserialize($row['goodsinfo']['fspecs']);
				$row['goodsinfo']['cover'] = $baseinfo['cover'];
				$list['list'][$key] = $row;
			}
		}
		return $list;
	}
	
	/***************************************************************************
	 * 查询商品的评价
	 ***************************************************************************/
	
	public function get_goods_comments($goodsid, $type = '', $page = 1, $size = 10, $offset = PAGE_OFFSET){
		$select = array('goodsid' => $goodsid);
		switch($type){
			case '1':
				$select['kept'] = " AND `score`>=1 AND `score`<2";
				break;
			case '2':
				$select['kept'] = " AND `score`>=2 AND `score`<3";
				break;
			case '3':
				$select['kept'] = " AND `score`>=3 AND `score`<4";
				break;
			case '4':
				$select['kept'] = " AND `score`>=4 AND `score`<5";
				break;
			case '5':
				$select['kept'] = " AND `score`=5";
				break;
		}
		$order = array('id' => 'DESC');
		$list = $this->db->get_list($this->tb_comment, '*', $select, $order, $page, $size, $offset);
		if(!empty($list['list'])){
			// $oOrder = & Order::instance();
			//$oGoods = & Goods::instance();
			foreach ($list['list'] as $key => $row){
				$row['addtime'] = ftime($row['addtime']);
				// 订单信息
				$row['goodsinfo'] = $this->get_order_goods($row['sn'], $row['goodsid']);
				$row['goodsinfo']['addtime'] = ftime($row['goodsinfo']['addtime'], 'addtime');
				$row['goodsinfo']['specs'] = unserialize($row['goodsinfo']['specs']);
				$row['goodsinfo']['fspecs'] = unserialize($row['goodsinfo']['fspecs']);
				$list['list'][$key] = $row;
			}
		}
		return $list;
	}	
}
?>